/*
* @Author: Adolphus.Yao
* @Date:   2019-07-23 17:17:49
* @Last Modified by:   Adolphus.Yao
* @Last Modified time: 2019-07-23 17:29:18
*/
package main

import (
    "flag"
    "bufio"
    "fmt"
    "io"
    "os"
    "strings"
    "regexp"
)

var (
    h bool
    file_path string
)

func init() {
    flag.BoolVar(&h, "h", false, "this help")
    flag.StringVar(&file_path, "f", "out.txt", "set json datas file")

    // 改变默认的 Usage，flag包中的Usage 其实是一个函数类型。这里是覆盖默认函数实现，具体见后面Usage部分的分析
    flag.Usage = usage
}

func main() {
    flag.Parse()

    if h {
        flag.Usage()
    } else {
        fi, err := os.Open(file_path)
        if err != nil {
            fmt.Printf("Error: %s\n", err)
            return
        }
        defer fi.Close()

        mp := make(map[string]map[string]string)
        br := bufio.NewReader(fi)
        lineNo := 0
        for {
            lineNo++
            line, err := br.ReadString('\n')
            line = strings.TrimSpace(line)
            if err != nil {
                if io.EOF == err {   //读取结束，会报EOF
                    break
                }
                fmt.Println(err, " err!!!!!!!!!! ", lineNo)
                continue
            }
            lineLen := len(line)
            if 0 < lineLen && strings.HasPrefix(line, "[yao]  c") {
                jIndex := strings.Index(line, "{")
                if 0 < jIndex {
                    re := regexp.MustCompile("\\s+")
                    line = re.ReplaceAllString(line, " ")
                    strs := strings.Split(line, " ")
                    if mpc, ok := mp[strs[1]]; ok {
                        mpc[strs[5]] = ""
                    } else {
                        mpc := make(map[string]string)
                        mpc[strs[5]] = ""
                        mp[strs[1]] = mpc
                    }
                } else {
                    fmt.Println("Error line can not find json char!", line, " ", lineNo)
                }
            } else {
                fmt.Println("Error line is invaild data!", line, " ", lineNo)
            }
        }
        fmt.Println(">>>>>>>>>>>>>>>", mp)
    }
}

func usage() {
    fmt.Fprintf(os.Stderr, `jcheck version: jcheck/1.0.0
Usage: jcheck

Options:
`)
    flag.PrintDefaults()
}
